/**
 * 批量周期运行
 * @author 木人心
 * @version 1.0.0
 */
import { FnOperationControl } from '@utils/object-util/periodic-execution/FnOperationControl'
import {
  PeriodicExecutionAddOption,
  PeriodicExecutionConstructorOption
} from '@utils/object-util/periodic-execution/type'

export class PeriodicExecution {
  private periodicMap = new Map<any, FnOperationControl>()

  constructor (option: PeriodicExecutionConstructorOption) {
    option.forEach((_option) => {
      this.add(_option)
    })
  }

  /**
   * 添加一条周期任务
   * @param option
   */
  public add (option: PeriodicExecutionAddOption) {
    this.periodicMap.set(option.key || option.fn, new FnOperationControl(option))
  }

  /**
   * 运行周期任务
   * @param key
   * @param rightRun
   * @param arg
   */
  public run (key?: any, rightRun = true, arg?: any[]) {
    if (key === undefined) {
      this.periodicMap.forEach(item => item.run(rightRun, arg))
    } else {
      this.periodicMap.get(key).run(rightRun, arg)
    }
  }

  /**
   * 停止周期任务
   * @param key
   */
  public stop (key?: any) {
    if (key === undefined) {
      this.periodicMap.forEach((item) => item.stop())
    } else {
      this.periodicMap.get(key).stop()
    }
  }

  /**
   * 移除周期任务
   * @param key
   */
  public remove (key?: any) {
    this.stop(key)
    if (key === undefined) {
      this.periodicMap.clear()
    } else {
      this.periodicMap.delete(key)
    }
  }

  /**
   * 销毁
   */
  public destroy () {
    this.remove()
  }
}
